<script>
  import FieldLabel from './FieldLabel.svelte';

  export let label = '';
  export let required = false;
  export let type = 'text';
  export let value = '';
  export let placeholder = '';
  export let options = []; // for select
  export let labelKey = 'label'; // 自定义label字段名
  export let valueKey = 'value'; // 自定义value字段名
  export let readonly = false;
  export let error = '';
  export let disabled = false;
  export let maxLength = null; // 新增：最大长度限制
  export let showCharacterCount = false; // 新增：控制是否显示字符计数
  
  // 验证函数
  export function validate() {
    if (required && (!value || value.toString().trim() === '')) {
      error = `请输入${label}`;
      return false;
    }
    
    // 最大长度校验
    if (maxLength && value && value.toString().length > maxLength) {
      error = `${label}不能超过${maxLength}个字符`;
      return false;
    }
    
    error = '';
    return true;
  }
  
  // 清除错误
  export function clearError() {
    error = '';
  }
  
  // 设置错误
  export function setError(msg) {
    error = msg;
  }
  
  // 输入事件处理
  function handleInput(event) {
    value = event.target.value;
    
    // 输入时清除错误，提供即时反馈
    if (error && value && value.toString().trim() !== '') {
      // 重新验证以提供实时反馈
      validate();
    }
  }
  
  function handleBlur() {
    // 失焦时进行完整验证
    validate();
  }
  
  // 获取选项的标签
  function getOptionLabel(option) {
    if (typeof option === 'string' || typeof option === 'number') {
      return option;
    }
    return option[labelKey] || option.label || option.name || option;
  }
  
  // 获取选项的值
  function getOptionValue(option) {
    if (typeof option === 'string' || typeof option === 'number') {
      return option;
    }
    return option[valueKey] || option.value || option.id || option;
  }
</script>

<div class="form-field">
  <FieldLabel {label} {required} />
  
  <div class="field-input">
    {#if readonly}
      <div class="readonly-value">{value || '-'}</div>
    {:else if type === 'select'}
      <select 
        bind:value 
        {disabled} 
        class:error={!!error}
        on:change={handleInput}
        on:blur={handleBlur}
      >
        <option value="">{placeholder || '请选择'}</option>
        {#each options as option}
          <option value={getOptionValue(option)}>
            {getOptionLabel(option)}
          </option>
        {/each}
      </select>
    {:else if type === 'textarea'}
      <textarea 
        bind:value 
        {placeholder} 
        {disabled}
        maxlength={maxLength}
        class:error={!!error}
        rows="3"
        on:input={handleInput}
        on:blur={handleBlur}
      ></textarea>
    {:else}
      <input 
        type={type}
        bind:value 
        {placeholder} 
        {disabled}
        maxlength={maxLength}
        class:error={!!error}
        on:input={handleInput}
        on:blur={handleBlur}
      />
    {/if}
  </div>
  
  <!-- 显示字符计数（当有最大长度限制且开启显示时） -->
  {#if maxLength && showCharacterCount && !readonly && (type === 'text' || type === 'textarea')}
    <div class="character-count" class:error={value && value.toString().length > maxLength}>
      {value ? value.toString().length : 0}/{maxLength}
    </div>
  {/if}
  
  {#if error}
    <div class="field-error">{error}</div>
  {/if}
</div>

<style>
  .form-field {
    margin-bottom: 24px;
  }
  
  .form-field:last-child {
    margin-bottom: 0;
  }
  
  .field-input input,
  .field-input select,
  .field-input textarea {
    width: 100%;
    padding: 8px 10px;
    border: 1px solid #e0e0e0;
    border-radius: 5px;
    font-size: 14px;
    background: #fff;
    box-sizing: border-box;
    color: #121212;
    transition: border-color 0.2s, box-shadow 0.2s;
    font-style: normal;
  }
  
  .field-input input::placeholder,
  .field-input textarea::placeholder {
    color: #ccc;
  }
  
  .field-input input:focus,
  .field-input select:focus,
  .field-input textarea:focus {
    outline: none;
    border: 1px solid rgba(69, 81, 229, 1);
    box-shadow: 0px 0px 2px 0px rgba(69, 81, 229, 0.6);

  }
  
  .field-input input:disabled,
  .field-input select:disabled,
  .field-input textarea:disabled {
    background: #f5f5f5;
    color: #ccc;
    cursor: not-allowed;
  }
  
  .field-input .error {
    border-color: #EE4646;
    background:  rgba(238, 70, 70, 0.05);

  }
  
  .field-input .error:focus {
    border-color: #EE4646;
     box-shadow: 0px 0px 3px 0px #EE4646;

  }
  
  .readonly-value {
    padding: 8px 0;
    font-size: 13px;
    color: #333;
    line-height: 1.5;
    word-break: break-all;
    min-height: 21px;
  }
  
  .field-error {
    margin-top: 4px;
    font-size: 12px;
    color: rgba(238, 70, 70, 1);
  }
  
  .field-input textarea {
    resize: vertical;
    min-height: 60px;
  }
  
  .character-count {
    margin-top: 4px;
    font-size: 11px;
    color: #999;
    text-align: right;
  }
  
  .character-count.error {
    color: rgba(238, 70, 70, 1);
  }
</style>
